package com.mashibing.remote;

import com.mashibing.internalcommon.constant.AmapConfigConstants;
import com.mashibing.internalcommon.dto.ResponseResult;
import com.mashibing.internalcommon.response.TerminalResponse;
import com.mashibing.internalcommon.response.TrsearchResponse;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class TerminalMapClient {


    @Value("${amap.key}")
    private String amapKey;

    @Value("${amap.sid}")
    private String sid;


    @Autowired
    private RestTemplate restTemplate;

    public ResponseResult<TerminalResponse> addTerminal(String name, String desc) {
        // 组装url
        StringBuilder urlBuild = new StringBuilder();
        urlBuild.append(AmapConfigConstants.TERMINAL_ADD);
        urlBuild.append("?");
        urlBuild.append("key=" + amapKey);
        urlBuild.append("&");
        urlBuild.append("name=" + name);
        urlBuild.append("&");
        urlBuild.append("sid=" + sid);
        urlBuild.append("&");
        urlBuild.append("desc=" + desc);
        log.info("高德地图：新增终端：" + urlBuild);

        // 请求远程地址
        ResponseEntity<String> directionEntity = restTemplate.postForEntity(urlBuild.toString(), null, String.class);
        JSONObject result = JSONObject.fromObject(directionEntity.getBody());
        String tid = result.getJSONObject("data").getString("tid");

        TerminalResponse terminalResponse = new TerminalResponse();
        terminalResponse.setTid(tid);
        log.info("高德地图：新增终端tid为：" + tid);

        return ResponseResult.success(terminalResponse);
    }

    public ResponseResult<List<TerminalResponse>> aroundsearch(String center, Integer radius) {

        // 组装url
        StringBuilder urlBuild = new StringBuilder();
        urlBuild.append(AmapConfigConstants.TERMINAL_AROUNDSEARCH);
        urlBuild.append("?");
        urlBuild.append("key=" + amapKey);
        urlBuild.append("&");
        urlBuild.append("sid=" + sid);
        urlBuild.append("&");
        urlBuild.append("center=" + center);
        urlBuild.append("&");
        urlBuild.append("radius=" + radius);

        log.info("高德地图  查询周边车辆" + urlBuild);

        ResponseEntity<String> directionEntity = restTemplate.postForEntity(urlBuild.toString(), null, String.class);
        String body = directionEntity.getBody();

        log.info("高德地图  返回查询信息" + body);

        JSONObject result = JSONObject.fromObject(body);
        JSONObject data = result.getJSONObject("data");

        List<TerminalResponse> terminalResponseList = new ArrayList<>();

        JSONArray results = data.getJSONArray("results");
        for (int i = 0; i < results.size(); i++) {
            TerminalResponse terminalResponse = new TerminalResponse();

            JSONObject jsonObject = results.getJSONObject(i);
            // desc是carId，
            String desc = jsonObject.getString("desc");
            Long carId = Long.parseLong(desc);
            String tid = jsonObject.getString("tid");

            JSONObject location = jsonObject.getJSONObject("location");
            String longitude = location.getString("longitude");
            String latitude = location.getString("latitude");

            terminalResponse.setCarId(carId);
            terminalResponse.setTid(tid);
            terminalResponse.setLongitude(longitude);
            terminalResponse.setLatitude(latitude);

            terminalResponseList.add(terminalResponse);
        }

        return ResponseResult.success(terminalResponseList);
    }

    public ResponseResult<TrsearchResponse> trackSearch(String tid, Long starttime, Long endtime) {

        // 拼装请求的url
        StringBuilder url = new StringBuilder();
        url.append(AmapConfigConstants.TERMINAL_TRSEARCH);
        url.append("?");
        url.append("key=").append(amapKey);
        url.append("&");
        url.append("sid=").append(sid);
        url.append("&");
        url.append("tid=").append(tid);
        url.append("&");
        url.append("starttime=").append(starttime);
        url.append("&");
        url.append("endtime=").append(endtime);

        System.out.println("高德地图查询轨迹结果请求：" + url);
        ResponseEntity<String> forEntity = restTemplate.getForEntity(url.toString(), String.class);
        System.out.println("高德地图查询轨迹结果响应：" + forEntity.getBody());

        JSONObject result = JSONObject.fromObject(forEntity.getBody());
        JSONObject data = result.getJSONObject("data");
        if (null == data) {
            System.out.println("高德地图查询轨迹无对应结果");
            return null;
        }

        int counts = data.getInt("counts");
        if (counts == 0) {
            System.out.println("高德地图查询轨迹无对应结果");
            return null;
        }

        JSONArray tracks = data.getJSONArray("tracks");
        long driveMile = 0L;
        long driveTime = 0L;
        for (int i = 0; i < tracks.size(); i++) {
            JSONObject jsonObject = tracks.getJSONObject(i);

            long distance = jsonObject.getLong("distance");
            driveMile = driveMile + distance;

            long time = jsonObject.getLong("time");
            time = time / (1000 * 60);
            driveTime = driveTime + time;
        }

        TrsearchResponse trsearchResponse = new TrsearchResponse();
        trsearchResponse.setDriveMile(driveMile);
        trsearchResponse.setDriveTime(driveTime);
        return ResponseResult.success(trsearchResponse);
    }
}
